#!/usr/bin/python3
"""
This is a command line tool for adding new repo
"""

import argparse
import yaml
import sys
from os import path
import subprocess

def get_info(pkg):
    nr = {}
    proc = subprocess.Popen(["rpm", "-qpi", pkg], stdout=subprocess.PIPE)
    while (True):
        line = proc.stdout.readline()
        if not line:
            break;
        info = str(line.strip().decode()).split(':')
        if (len(info) < 2):
            continue
        info[0] = info[0].strip()
        info[1] = info[1].strip()
        if (info[0] == "Name"):
            nr["name"] = info[1]
        elif (info[0] == "Summary"):
            nr["description"] = info[1]
        elif (info[0] == "URL"):
            if (len(info) >= 3):
                nr["upstream"] = info[1] + ":" + info[2]
            else:
                nr["upstream"] = info[1]


    proc.stdout.close()
    proc.wait()

    return nr

if __name__ == "__main__":
    par = argparse.ArgumentParser()
    par.add_argument("-r", "--repo", help="YAML file for repositories", type=str, required=True)
    par.add_argument("-i", "--sigs", help="YAML file for sigs", type=str, required=True)
    par.add_argument("-s", "--sig", help="The SIG which contains the package", type=str, required=True)
    par.add_argument("-p", "--pkg", help="Package for upoad", type=str, required=True)

    args = par.parse_args()

    nr = {}
    if (path.exists(args.pkg) and path.isfile(args.pkg)):
        nr = get_info(args.pkg)
        if (len(nr) < 3):
            print("Failed to parse the output of rpm -qpi {pkg}".format(pkg=args.pkg))
            sys.exit(1)
    else:
        print("%s does not exist\n" & args.pkg)
        sys.exit(1)

    f = open(args.sigs)
    sigs = yaml.load(f.read(), Loader=yaml.Loader)
    if not sigs:
        print("Failed to load {file}".format(file=args.sigs))
        sys.exit(1)
    f.close()

    f = open(args.repo)
    repo = yaml.load(f.read(), Loader=yaml.Loader)
    if not repo:
        print("Failed to load {file}".format(file=args.repo))
        sys.exit(1)
    f.close()

    nr["protected_branches"] = ["master"]
    nr["type"] = "public"

    exist = [x for x in repo["repositories"] if x["name"] == nr["name"]]
    if exist != []:
        print("Repo already exist")
        sys.exit(1)

    if repo["community"] == "openeuler":
        del nr["upstream"]
        repo["repositories"].append(nr)
    elif repo["community"] == "src-openeuler":
        repo["repositories"].append(nr)

    repo["repositories"].sort(key=lambda r: r["name"])

    valid_sig = False
    for s in sigs["sigs"]:
        if s["name"] == args.sig:
            s["repositories"].append(repo["community"] + "/" + nr["name"])
            s["repositories"].sort()
            valid_sig=True
            continue

    if valid_sig:
        f = open(args.repo, "w")
        yaml.dump(repo, f, sort_keys=False)
        f.close()
        f = open(args.sigs, "w")
        yaml.dump(sigs, f, sort_keys=False)
        f.close()
    else:
        print("SIG name is not valid")
        sys.exit(1)


    print("create repo %s successfully\n" % nr["name"])
    sys.exit(0)
